import React from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { Form, Input, Button, message } from "antd";

// eslint-disable-next-line no-unused-vars
import { login, loginSuccess } from "../../store/features/userSlice";

import "./index.scss";

export default function Login() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  /**
   * 表单提交，且校验通过时触发
   */
  // function onFinish(values) {
  //   console.log("onFinish", values);
  //   // 调用接口登录，登录成功需要将用户信息与token给存下来
  //   // 存到哪里？ 状态管理器中 redux

  //   dispatch(login(values))
  //     .then(() => {
  //       // 登录成功
  //       message.success("登录成功");
  //     })
  //     .catch((error) => {
  //       // 登录失败
  //       console.log("dispatch catch", error);
  //       message.error(error.message || "网络异常,请稍后重试");
  //     });
  // }

  async function onFinish(values) {
    // 调用接口,成功之后,派发动作将数据存入仓库
    const { data } = await axios.post("http://localhost:5000/login", values);
    if (data.code === 0) {
      // 登录成功
      message.success("登录成功");
      // 存入仓库
      dispatch(loginSuccess(data.data));
      // 本地存储也放一份
      // window.localStorage.setItem("user", JSON.stringify(data.data));
      // 跳转到首页
      navigate("/", { replace: true });
    } else {
      // 登录失败
      message.error(data.msg);
    }
  }

  function onFinishFailed() {
    console.log("onFinishFailed");
  }

  return (
    <div className="login">
      <Form
        className="login-form"
        name="basic"
        labelCol={{
          span: 6,
        }}
        wrapperCol={{
          span: 16,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[
            {
              required: true,
              message: "Please input your username!",
            },
          ]}
        >
          <Input />
        </Form.Item>

        {/* <Form.Item
          label="Email"
          name="email"
          rules={[
            {
              required: true,
              message: "请输入邮箱地址",
            },
            {
              type: "email",
              message: "请填写正确的邮箱地址",
            },
          ]}
        >
          <Input />
        </Form.Item> */}

        <Form.Item
          label="Password"
          name="password"
          rules={[
            {
              required: true,
              message: "Please input your password!",
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 6,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
